﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using BP.OA;
namespace CCOA.App.News
{
    public partial class NewsAdd : System.Web.UI.Page
    {
        #region //1.公共接口(Public Interface)
        //权限控制
        private string FuncNo = null;
        private string CurUserNo
        {
            get { return BP.Web.WebUser.No; }
        }
        private void Alert(string msg)
        {
            BP.OA.Debug.Alert(this, msg);
        }
        private DataTable GetArticleCataogry()
        {
            //返回目录必须为两个字段，第一字段为Key值，字第二字段为Name值
            BP.OA.ArticleCatagorys f = new ArticleCatagorys();
            return f.RetrieveAllToTable();
            //string sSql = "Select No,Name from OA_ArticleCatagory order by No";
            //return BP.DA.DBAccess.RunSQLReturnTable(sSql);
        }
        private int News_Insert(String FK_ArticleCatagory,String Title,String KeyWords,String Doc,String ArticleSource,String AttachFile)
        {
            BP.OA.Article arNew = new BP.OA.Article();
            arNew.AddTime = BP.DA.DataType.CurrentDataTime; 
            arNew.FK_UserNo = BP.Web.WebUser.No;
            arNew.FK_ArticleCatagory = FK_ArticleCatagory;
            arNew.Title = Title;
            arNew.KeyWords = KeyWords;
            arNew.ArticleSource = ArticleSource;
            arNew.Doc = Doc;
            arNew.AttachFile = AttachFile;
            arNew.Insert();
            arNew.Doc = Doc;
            arNew.Update();
            return arNew.OID;
        }
        /// <summary>
        /// 获取路径函数
        /// </summary>
        /// <returns></returns>
        private string GetAttachPathName()
        {
            string dir = String.Format("/DataUser/UploadFile/Article/{0:yyyyMMdd}", DateTime.Now);
            return dir;
        }
        /// <summary>
        /// 获取新文件名函数
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private string GetAttachFileName(string fileName)
        {
            string f = System.IO.Path.GetFileNameWithoutExtension(fileName);
            string ext = System.IO.Path.GetExtension(fileName);
            string newFileName = String.Format("{0}_{1:yyyyMMddHHmmss}{2}", f, DateTime.Now, ext);
            return newFileName;
        }
        #endregion

        #region //2.页面装载(Page Load)
        protected void Page_Init(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (!BP.OA.GPM.IsCanUseFun(this.FuncNo)) { BP.OA.GPM.RedirectNoAccess(); return; }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.LoadData();
            }
        }
        private void LoadData()
        {
            BP.OA.UI.Dict.BindListCtrl(this.GetArticleCataogry(), this.ui_ArticleCatagory, "Name", "No", null, null, null);
        }
        #endregion

        #region //3.页面事件(Page Event)
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            //0.用户权限
            if (!BP.OA.GPM.IsCanUseFun(this.FuncNo)) { BP.OA.GPM.RedirectNoAccess(); return; }
            //1.获取用户变量
            String curUserNo = BP.Web.WebUser.No;
            String ArticleCatagory = this.ui_ArticleCatagory.SelectedValue;
            String Title = this.ui_Title.Text;
            String KeyWords = this.ui_KeyWords.Text;
            String ArticleSource = this.ui_ArticleSource.Text;
            String Doc = this.ui_Doc.Text;
            //2.数据验证
            StringBuilder sbErr = new StringBuilder();
            if (String.IsNullOrEmpty(Title.Trim()))
            {
                sbErr.Append("新闻标题不能为空！");
            }
            if (String.IsNullOrEmpty(Doc.Trim()))
            {
                sbErr.Append("新闻内容不能为空！");
            }
            
            if (sbErr.Length != 0)
            {
                this.Alert(sbErr.ToString());
                return;
            }
            //3.数据处理
            string AttachFile = null;
            string dir = this.GetAttachPathName();
            if (!System.IO.Directory.Exists(Server.MapPath(dir)))
                 System.IO.Directory.CreateDirectory(Server.MapPath(dir));
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                
                if (hpf.ContentLength > 0)
                {
                    string newFileName = this.GetAttachFileName(hpf.FileName);
                    string path = String.Format("{0}/{1}", dir, newFileName);
                    //string filePath = this.FileUpload1.PostedFile.FileName;
                    try
                    {
                        hpf.SaveAs(Server.MapPath(path));
                        AttachFile += String.Format("{0};", path);
                    }
                    catch
                    {
                        ;
                    }
                }
            }
            bool blnOpe = false;
            int newsId=this.News_Insert(ArticleCatagory, Title, KeyWords, Doc, ArticleSource, AttachFile);
            blnOpe = newsId != 0;
            //4.统计/日志
            //5.提示处理信息            
            if (blnOpe)
            {
                //发短消息
                if (this.cbMsg.Checked)
                {
                    string userNos=BP.OA.Main.GetValueListFromDataRowArray(BP.OA.GPM.GetAllEmps().Select(), "{0}", ",", "No");
                    BP.OA.ShortMsg.Send_News(userNos, Title, "", newsId.ToString(),false);
                }
                //this.Alert("添加文章成功");
                this.Response.Redirect("~/App/News/NewsList.aspx", true);
            }
            else
                this.Alert("添加文章失败");
        }
        #endregion
    }
}